<template>
  <!-- 用户购买记录-->
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      inline
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item prop="serviceTypeName">
        <el-select
          v-model="queryParams.serviceTypeName"
          placeholder="请选择服务类型"
          filterable
          @change="serviceTypeQuery"
        >
          <el-option
            v-for="item in serivceTypeList"
            :key="item.type"
            :label="item.name"
            :value="item.name"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="productTypeId">
        <el-select
          v-model="queryParams.productTypeId"
          placeholder="请选择产品类型名称"
          filterable
          @change="productTypeQuery"
        >
          <el-option
            v-for="item in productTypeList"
            :key="item.type"
            :label="item.name"
            :value="item.type"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="productName">
        <el-select
          v-model="queryParams.productName"
          placeholder="请选择产品名称"
          filterable
          @change="productChange"
        >
          <el-option
            v-for="(item, k) in productList"
            :key="k"
            :label="item.productName"
            :value="item.productName"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="用户昵称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item prop="dateRange">
        <el-date-picker
          v-model="dateRange"
          type="datetimerange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH:mm:ss"
          :default-time="['00:00:00', '23:59:59']"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
          >查询</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="add-box">
      <el-button type="primary" plain size="mini" @click="addBuyRecord"
        >添加购买记录</el-button
      >
      <el-button type="warning" plain size="mini" @click="handleDel()"
        >删除购买记录</el-button
      >
      <el-button type="primary" plain size="mini" @click="exportExcel">导出</el-button>
    </div>
    <div class="statistics">
      <div class="statistics-item">
        <div>数据统计：</div>
        <div>
          购买总条数：<span>{{ allCount }}</span>
        </div>
        <div>
          购买总金额：<span>{{ allAmount || 0 }}元</span>
        </div>
        <div>
          使用单位数：<span>{{ allUser || 0 }}</span>
        </div>
      </div>
      <div id="sales" />
    </div>
    <!-- 表格 -->
    <el-table
      v-loading="loading"
      border
      :data="dataList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" align="center" width="55" />
      <el-table-column label="用户昵称" align="center" prop="nickName" />
      <el-table-column label="服务类型" align="center" prop="serviceTypeName" />
      <el-table-column label="产品类型" align="center" prop="productTypeName" />
      <el-table-column label="产品名称" align="center" prop="productName" />
      <el-table-column label="数量" align="center" prop="productCount" />
      <el-table-column label="金额" align="center" prop="amount" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button type="text" size="mini" @click="handleDel(scope.row)"
            >删除</el-button
          >
          <el-button type="text" size="mini" @click="handleView(scope.row)"
            >查看</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!--分页  -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.params.pageNum"
      :limit.sync="queryParams.params.pageSize"
      @pagination="getList"
    />

    <!-- 添加 -->
    <el-dialog
      title="添加购买记录"
      :visible.sync="addShow"
      width="60%"
      :close-on-click-modal="false"
      @close="cancelForm"
    >
      <el-form ref="addForm" :model="addForm" label-width="100px" :rules="rules">
        <el-form-item label="用户昵称" prop="userId">
          <el-select
            v-model="addForm.userId"
            placeholder="请选择用户"
            clearable
            filterable
            @change="changeUser"
          >
            <el-option
              v-for="item in userlist"
              :key="item.userId"
              :label="item.nickName"
              :value="item.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="服务类型" prop="serviceTypeName">
          <el-select
            v-model="addForm.serviceTypeName"
            placeholder="请选择服务类型"
            clearable
            filterable
            @change="changeServiceType"
          >
            <el-option
              v-for="item in serivceTypeList"
              :key="item.type"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="产品类型" prop="productTypeId">
          <el-select
            v-model="addForm.productTypeId"
            placeholder="请选择产品类型名称"
            clearable
            filterable
            @change="productTypeChange"
          >
            <el-option
              v-for="item in productTypeList"
              :key="item.type"
              :label="item.name"
              :value="item.type"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="添加产品" prop="productName">
          <el-select
            v-model="productName"
            placeholder="点击产品添加"
            clearable
            filterable
            @change="productChange"
          >
            <el-option
              v-for="(item, k) in productList"
              :key="k"
              :label="item.productName"
              :value="k"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="产品列表" prop="list">
          <el-table :data="addForm.list" style="width: 100%">
            <el-table-column prop="productName" label="产品名称" min-width="100">
              <template slot-scope="scope">
                <el-input v-model="scope.row.productName" placeholder="请输入产品名称" />
              </template>
            </el-table-column>
            <el-table-column prop="productConfig" label="产品配置" min-width="160">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.productConfig"
                  placeholder="请输入产品配置"
                />
              </template>
            </el-table-column>
            <el-table-column prop="productCount" label="产品数量" min-width="80">
              <template slot-scope="scope">
                <el-input v-model="scope.row.productCount" placeholder="请输入产品数量" />
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="金额" min-width="80">
              <template slot-scope="scope">
                <el-input v-model="scope.row.amount" placeholder="请输入金额" />
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" min-width="160">
              <template slot-scope="scope">
                <div style="display: flex; align-items: center">
                  <el-input v-model="scope.row.remark" placeholder="请输入产品配置" />
                  <i
                    class="el-icon-delete"
                    style="margin-left: 10px; color: #f00"
                    @click="handleDelete(scope.$index)"
                  />
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="addHandleSure">确 定</el-button>
        <el-button @click="cancelForm">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 修改 -->
    <el-dialog title="修改购买记录" :visible.sync="editShow" width="40%" :close-on-click-modal="false">
      <el-form ref="addForm" :model="addForm" label-width="100px" :rules="rules">
        <el-form-item label="用户昵称" prop="userId">
          <el-select
            v-model="addForm.userId"
            placeholder="请选择用户"
            clearable
            @change="changeUser"
          >
            <el-option
              v-for="item in userlist"
              :key="item.userId"
              :label="item.nickName"
              :value="item.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="服务类型" prop="serviceTypeName">
          <el-input
            v-model="addForm.serviceTypeName"
            placeholder="请输入产品类型"
            disabled
          />
        </el-form-item>
        <el-form-item label="产品类型" prop="productTypeName">
          <el-input
            v-model="addForm.productTypeName"
            placeholder="请输入产品类型"
            disabled
          />
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="addForm.productName" placeholder="请输入产品名称" />
        </el-form-item>
        <el-form-item label="数量" prop="productCount">
          <el-input v-model="addForm.productCount" />
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input v-model="addForm.amount" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="addForm.remark" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="addHandleSure">确 定</el-button>
        <el-button @click="cancelForm">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 详情 -->
    <el-dialog title="详情" :visible.sync="detailShow" width="50%" :close-on-click-modal="false">
      <el-form :model="detailRow" label-width="100px">
        <div class="flex">
          <div>
            <el-form-item label="用户昵称">{{ detailRow.nickName || "-" }}</el-form-item>
            <el-form-item label="服务名称">{{
              detailRow.serviceTypeName || "-"
            }}</el-form-item>
            <el-form-item label="数量">{{ detailRow.productCount || "-" }}</el-form-item>
            <el-form-item label="配置参数">{{
              detailRow.productConfig || "-"
            }}</el-form-item>
            <el-form-item label="备注">{{ detailRow.remark || "-" }}</el-form-item>
          </div>
          <div>
            <el-form-item label="产品名称">
              {{ detailRow.productName || "-" }}</el-form-item
            >
            <el-form-item label="产品类型">{{
              detailRow.productTypeName || "-"
            }}</el-form-item>
            <el-form-item label="金额">{{ detailRow.amount || 0 }} 元</el-form-item>
            <el-form-item label="创建时间">{{
              detailRow.createTime || "-"
            }}</el-form-item>
          </div>
        </div>
      </el-form>
      <div slot="footer">
        <el-button @click="detailShow = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as echarts from "echarts";
import {
  virtuallyLogList,
  addVirtuallyLog,
  updateVirtuallyLog,
  delVirtuallyLog,
  virtuallyUserList,
  virtuallyProductList,
  virtuallyProductTypeList,
  virtuallyExport,
  virtuallyStatistics,
} from "@/api/systemManagement/userBuyRecord";

export default {
  data() {
    return {
      loading: false, // 遮罩层
      showSearch: true, // 显示搜索条件
      total: 0, // 总条数
      dataList: [], // 充值管理表格数据
      // 查询参数
      queryParams: {
        productTypeId: "",
        productTypeName: "",
        productName: "",
        beginTime: "",
        endTime: "",
        params: {
          pageNum: 1,
          pageSize: 10,
        },
      },
      dateRange: [], // 日期范围
      detailRow: {}, //详情内容
      detailShow: false, //详情弹窗开关
      addShow: false, //添加弹窗开关
      editShow: false, // 编辑弹窗开关
      addForm: {
        list: [],
      }, //添加的内容
      rules: {
        //添加表单验证
        userId: [{ required: true, message: "请选择用户", trigger: "change" }],
        nickName: [{ required: true, message: "请选择用户昵称", trigger: "change" }],
        serviceTypeName: [
          { required: true, message: "请选择服务类型", trigger: "change" },
        ],
        productTypeName: [
          { required: true, message: "请输入产品类型", trigger: "change" },
        ],
        productCount: [
          { required: true, message: "请输入产品数量", trigger: "change" },
        ],
        amount: [{ required: true, message: "请输入金额", trigger: "change" }],
      },
      userlist: [], //虚拟用户列表
      serivceTypeId: "", // 服务类型id
      serivceTypeList: [], //服务类型列表
      productTypeList: [], //产品类型列表
      productList: [], // 产品列表
      productName: "", // 产品名称
      allAmount: 0, //总金额
      allCount: 0, //总条数
      allUser: 0, //总用户数
    };
  },
  created() {
    //获取表格数据
    this.getList();
    //获取虚拟用户列表
    this.getUserList();
    this.getServeList();
  },
  methods: {
    /**用户昵称 */
    changeUser(val) {
      const findUser = this.userlist.find((item) => item.userId === val);
      this.addForm.nickName = findUser ? findUser.nickName : "";
    },
    /**统计 */
    statistics() {
      virtuallyStatistics(this.queryParams).then((res) => {
        if (200 == res.code) {
          this.allAmount = res.data.amount;
          this.allCount = res.data.count;
          this.allUser = res.data.userCount;
          this.drawChart();
        }
      });
    },
    // 图表
    drawChart() {
      let sales = document.getElementById("sales");
      if (sales.hasAttribute("_echarts_instance_"))
        sales.removeAttribute("_echarts_instance_");
      var myChart = echarts.init(sales);
      let option = {
        tooltip: {
          trigger: "axis",
          axisPointer: { type: "shadow" },
        },
        grid: {
          top: "3%",
          left: "0%",
          right: "0%",
          bottom: "0%",
          containLabel: true,
        },
        xAxis: [
          {
            type: "category",
            data: ["用户数量", "金额"],
            axisTick: { alignWithLabel: true },
          },
        ],
        yAxis: {
          splitLine: {
            show: true,
            lineStyle: { type: "dashed" },
          },
        },
        series: {
          type: "bar",
          barWidth: "60px",
          itemStyle: {
            normal: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: "#4098ff" },
                { offset: 0.5, color: "rgba(64, 152, 255, 0.5)" },
                { offset: 1, color: "rgba(64, 152, 255, 0.2)" },
              ]),
            },
          },
          data: [this.allUser, this.allAmount],
        },
      };
      myChart.setOption(option, true, true);
      window.addEventListener("resize", () => {
        myChart.resize();
      });
    },
    /**导出 */
    exportExcel() {
      virtuallyExport(this.queryParams).then((res) => {
        let alink = document.createElement("a");
        alink.href = window.URL.createObjectURL(new Blob([res.data]));
        alink.download = "购买记录.xlsx";
        alink.click();
        alink.remove();
      });
    },
    /**多选 */
    handleSelectionChange(val) {
      this.ids = val.map((item) => item.id);
    },
    /**删除分类 */
    handleDel(row) {
      let id = row ? [row.id] : this.ids;
      this.$modal
        .confirm(`是否确认删除这条购买记录吗?`)
        .then(() => {
          delVirtuallyLog(id).then((res) => {
            if (200 == res.code) {
              this.getList();
              this.$message.success("删除成功！");
            }
          });
        })
        .catch(() => {});
    },
    /**查询虚拟用户列表 */
    getUserList() {
      virtuallyUserList().then((res) => {
        if (200 == res.code) {
          for (const key in res.data) {
            this.userlist.push({ userId: key, nickName: res.data[key] });
          }
        }
      });
    },
    /**查询服务类型列表 */
    getServeList() {
      virtuallyProductTypeList().then((res) => {
        if (200 == res.code) {
          this.serivceTypeList = res.data.map((i) => {
            return {
              ...i,
              children: i.children
                ? i.children.map((j) => {
                    return {
                      name: j.name,
                      type: j.id,
                    };
                  })
                : [],
            };
          });
        }
      });
    },
    // 获取服务类型
    serviceTypeQuery(e) {
      let row = this.serivceTypeList.find((item) => item.name == e);
      this.serivceTypeId = row.type;
      this.productTypeList = row.children;
      this.queryParams.productTypeId = "";
      this.queryParams.productTypeName = "";
      this.queryParams.productName = "";
      this.productList = [];
    },
    // 获取产品类型
    productTypeQuery(type) {
      let row = this.productTypeList.find((item) => item.type == type);
      this.queryParams.productTypeName = row.name;
      this.queryParams.productName = "";
      virtuallyProductList(this.serivceTypeId, type).then((res) => {
        this.productList = res.data;
      });
    },
    // 改变服务类型
    changeServiceType(e) {
      let row = this.serivceTypeList.find((item) => item.name == e);
      this.serivceTypeId = row.type;
      this.productTypeList = row.children;
    },
    // 改变产品类型
    productTypeChange(type) {
      let row = this.productTypeList.find((item) => item.type == type);
      this.addForm.productTypeName = row.name;
      virtuallyProductList(this.serivceTypeId, type).then((res) => {
        this.productList = res.data;
      });
    },
    // 改变产品
    productChange(e) {
      let row = this.productList[e];
      this.productName = "";
      this.addForm.list.push(row);
    },
    // 删除产品
    handleDelete(index) {
      this.addForm.list.splice(index, 1);
    },
    /**打开添加弹窗 */
    addBuyRecord() {
      this.addShow = true;
      this.addForm = {
        list: [],
      };
      this.resetForm("addForm");
    },
    /**打开修改弹窗 */
    handleUpdate(row) {
      this.addForm = Object.assign({}, row);
      this.editShow = true;
    },
    /**确认添加 & 修改 */
    addHandleSure() {
      this.$refs["addForm"].validate((valid) => {
        if (valid) {
          let request = this.addForm.id ? updateVirtuallyLog : addVirtuallyLog;
          request(this.addForm).then((res) => {
            if (200 == res.code) {
              this.getList();
              this.addShow = false;
              this.editShow = false;
              this.$message.success(
                this.addForm.id ? "修改购买记录成功" : "添加购买记录成功"
              );
            }
          });
        }
      });
    },
    /**关闭添加 & 修改对话框 */
    cancelForm() {
      this.resetForm("addForm");
      this.productTypeList = [];
      this.productList = [];
      this.addShow = false;
      this.editShow = false;
    },
    /**查看详情 */
    handleView(row) {
      this.detailRow = Object.assign({}, row);
      this.detailShow = true;
    },
    /** 查询购买记录信息列表 */
    getList() {
      if (this.dateRange && this.dateRange.length) {
        this.queryParams.beginTime = this.dateRange[0];
        this.queryParams.endTime = this.dateRange[1];
      } else {
        this.queryParams.beginTime = "";
        this.queryParams.endTime = "";
      }
      this.loading = true;
      virtuallyLogList(this.queryParams)
        .then((res) => {
          this.dataList = res.rows;
          this.total = res.total;
          this.statistics();
        })
        .finally(() => {
          this.loading = false;
        });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.params.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.queryParams.productTypeName = "";
      this.resetForm("queryForm");
      this.handleQuery();
    },
  },
};
</script>

<style lang="scss" scoped>
.add-box {
  margin-bottom: 20px;
}

.flex {
  display: flex;

  > div {
    flex: 1;
  }
}

.el-select {
  width: 100%;
}

.statistics {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  min-height: 100px;
  border: 1px solid #ccc;
  .statistics-item {
    flex: 1;
    font-weight: bold;
    color: #8f8f8f;
    div {
      height: 40px;
      span {
        color: #000;
      }
    }
  }
  #sales {
    flex: 1;
    width: 50%;
    height: 200px;
  }
}
</style>
